package com.masu.knows.portal.service.impl;

import com.masu.knows.portal.exception.ServiceException;
import com.masu.knows.portal.mapper.UserMapper;
import com.masu.knows.portal.model.Comment;
import com.masu.knows.portal.mapper.CommentMapper;
import com.masu.knows.portal.model.User;
import com.masu.knows.portal.service.ICommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.masu.knows.portal.vo.CommentVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 沈传尚
 * @since 2021-12-07
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements ICommentService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private CommentMapper commentMapper;

    @Override
    public Comment saveComment(CommentVo commentVo, String username) {
        // 获取当前用户对象
        User user = userMapper.findUserByUsername(username);
        Comment comment=new Comment();
        if (Objects.nonNull(user)){
            comment.setUserId(user.getId())
                    .setUserNickName(user.getNickname())
                    .setAnswerId(commentVo.getAnswerId())
                    .setContent(commentVo.getContent());
            int row = commentMapper.insert(comment);
            if (row != 1){
                throw new ServiceException("新增数据异常");
            }
        }
        return comment;
    }

    @Override
    public boolean removeComment(Integer commentId, String username) {
        User user = userMapper.findUserByUsername(username);
        // 老师
        if (Objects.equals(user.getType(),1)){
            return 1 == commentMapper.deleteById(commentId);
        }

        // 学生
        if (Objects.equals(user.getType(),0)){
            Comment comment = commentMapper.selectById(commentId);
            // 判断该评论是否为学生本人发布
            if (Objects.equals(comment.getUserId(),user.getId())){
                int num = commentMapper.deleteById(commentId);
                return num == 1;
            }
        }

        throw new ServiceException("没有权限删除该评论");
    }

    @Override
    @Transactional
    public Comment updateComment(Integer commentId, CommentVo commentVo, String username) {
        Comment comment = commentMapper.selectById(commentId);
        User user = userMapper.findUserByUsername(username);

        // 老师或者本人操作都可以
        if (Objects.equals(user.getType(),1) || Objects.equals(comment.getUserId(),user.getId())){
            comment.setContent(commentVo.getContent());
            int num = commentMapper.updateById(comment);
            if (num != 1){
                throw new ServiceException("修改数据异常");
            }
            return comment;
        }

        throw new ServiceException("没有权限修改该评论!");
    }
}
